package com.lg.startertemplate.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.lg.startertemplate.domain.jdbc.DataSourceConfig;
import com.lg.startertemplate.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理  有限个 数据源
 *
 * 数据源可自动生成 todo
 * 数据源可自动获取 todo
 */


@Slf4j
@Component
public class DataSourceManager {
    //数据源最多5个
    public final static Integer COUNT = 5;
    //所有的数据源 可以通过key 获取
    public final static  Map<String, DruidDataSource> DATASOURCE = new ConcurrentHashMap<>();


    /**
     * 添加数据源
     */
//    @EventListener(ApplicationReadyEvent.class)
    public  DruidDataSource createDatasource(DataSourceConfig dataSourceConfig){
        log.info("创建新数据源: " +dataSourceConfig.getName());

        if (this.DATASOURCE.size() > this.COUNT) {
            throw new CommonException("数据源超过最大限制: "+this.COUNT +" 无法在创建");
        }

        DruidDataSource instance = new DruidDataSource();
        try {
            instance.setDriverClassName(dataSourceConfig.getDriver());
            instance.setUrl(dataSourceConfig.getUrl());
            instance.setPassword(dataSourceConfig.getPassword());
            instance.setUsername(dataSourceConfig.getUser());
            instance.setInitialSize(dataSourceConfig.getInitialSize());
            instance.setMinIdle(dataSourceConfig.getMinIdle());
            instance.setMaxActive(dataSourceConfig.getMaxActive());
            instance.setMaxWait(dataSourceConfig.getMaxWait());
            instance.setTimeBetweenEvictionRunsMillis(dataSourceConfig.getTimeBetweenEvictionRunsMillis());
            instance.setMinEvictableIdleTimeMillis(dataSourceConfig.getMinEvictableIdleTimeMillis());
            this.DATASOURCE.put(dataSourceConfig.getName(), instance);
            return instance;
        } catch (Exception e) {
            log.error("创建数据源出错",e);
        }
        return null;
    }

    public DruidDataSource getDatasource(String datasourceName){
        return this.DATASOURCE.get(datasourceName);
    }

}
